
class ChatController {

	def text = ''

	/**
		@description
			แอ็กชั่น index จะรับ parameter 2 ตัวคือ
			1. params.id เป็นชื่อ user
			2. params.msg (ไม่บังคับ)
		@see
			conf/UrlMappings.groovy: /chat/$id/$msg?
	**/
    def index = {     	
    	def curUser = User.findByName(params.id)
    	if(curUser == null) {
    		curUser = new User(name:params.id).save()
    	}
    	def oldLog = curUser.lastLog
    	// ถ้าระบุ msg หมายถึงมีการพิมพ์ข้อความเข้ามา
    	if(params.msg != null) {
    		def newLog = new ChatLog(user:curUser, msg:params.msg).save()
	    	curUser.lastLog = newLog
	    	curUser.save()    	    		
		} else {
			curUser.lastLog = ChatLog.listOrderById(max:1, order:'desc')[0]
			curUser.save()
		}
    	if(oldLog == null && curUser.lastLog == null) {
    		render(text:'')	
    		return
    	}
    	def from = 0
    	def to = 0
    	if(oldLog == null && curUser.lastLog.user.id != curUser.id) {
			from = 0; to = curUser.lastLog.id
		} else if (oldLog == null){
			from = 0; to = curUser.lastLog.id - 1
		} else if (curUser.lastLog.user.id != curUser.id) {
			from = oldLog.id + 1; to = curUser.lastLog.id
		} else {
			from = oldLog.id + 1; to = curUser.lastLog.id - 1
		}
		def logs = ChatLog.findAllByIdBetween(from, to)
    	logs.each {
    		text += "<b>${it.user.name}</b>: ${it.msg}\n"
    	}
    	render(text: text)
    }
    
}
